package com.chen.reggie.aspect;

import com.chen.reggie.dto.DishDto;
import com.chen.reggie.pojo.Dish;
import com.chen.reggie.service.DishService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName DishAspect
 * @Description TODO
 * @Author hainc
 * @Date 2022/9/11 14:58
 * @Version 1.0
 * 缓存清空切面类
 **/
//@Component
//@Aspect
public class DishAspect {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishService dishService;

    //环绕通知，可以拿到传递参数
    @Around(value = "dishSaveAndUpdateCut()")
    public Object dishAroundCut(ProceedingJoinPoint pjp) throws Throwable{
        //前置通知和后置通知都会经过这方法，所以总共会经过2次该方法
        Object[] args = pjp.getArgs();
        if(args[0] instanceof DishDto){//如果是dishDto类，代表修改和添加的菜品方法,删除对应的redis缓存数据
            DishDto dishDto = (DishDto) args[0];
            String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
            redisTemplate.delete(key);
        }else if(args[0] instanceof List){ //代表是删除菜品redis缓存数据
            List<Long> ids = (List<Long>) args[0];
            Long aLong = ids.get(0);
            Dish dish = dishService.getById(aLong);
            String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
            redisTemplate.delete(key);
        }


        Object proceed = pjp.proceed(args);//把修改后的数据传递回去

        return proceed;
    }

    //切点起别名，代表切修改和添加菜品加入切点，删除缓存
//    @Pointcut(value = "execution(* com.chen.reggie.service.impl.DishServiceImpl.*(..))")
    @Pointcut(value = "execution(* com.chen.reggie.service.DishService.*(..))")
    public void dishSaveAndUpdateCut(){}
}
